package com.cn.codebrush.数字;

import java.util.Arrays;

public class No556下一个更大元素III {
    public static void main(String[] args) {
        System.out.println(nextGreaterElement(2147483486));

    }

    public static int nextGreaterElement(int n) {
        String temp = ""+n;
        int len = temp.length();
        if(len == 1){
            return -1;
        }
        int pop = 0;
        int count = n;
        int[] nums = new int[len];
        int k = len-1;
        while(count != 0){
            pop = count%10;
            nums[k] = pop;
            count = count/10;
            k--;
        }

        int[] newNums = nextGreaterElementHelper(nums);

        int val = 0;
        for(int p=0;p<len;p++){
            if(val > (Integer.MAX_VALUE-newNums[p])/10){
                return -1;
            }
            val = val*10+newNums[p];
        }

        return  val==0?-1:val;
    }


    public static int[] nextGreaterElementHelper(int[] nums) {

        for(int i=nums.length-1;i>0;i--){
            if(nums[i]>nums[i-1]){
                Arrays.sort(nums,i,nums.length);
                for(int j=i;j<nums.length;j++){
                    if(nums[j] > nums[i-1]){
                        int t = nums[i-1];
                        nums[i-1] = nums[j];
                        nums[j] = t;
                       return nums;
                    }
                }
            }

            if(i == 1){
                return new int[nums.length];
            }
        }

        return nums;
    }
}
